package com.cs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs.annotation.AutoAnnouncement;
import com.cs.constant.RedisConstant;
import com.cs.context.BaseContext;
import com.cs.domain.Course;
import com.cs.domain.StudentCourse;
import com.cs.domain.User;
import com.cs.dto.EditUserDTO;
import com.cs.dto.RegisterUserDTO;
import com.cs.enumeration.OperationType;
import com.cs.exception.BaseException;
import com.cs.mapper.ICourseMapper;
import com.cs.mapper.IStudentCourseMapper;
import com.cs.mapper.IUserMapper;
import com.cs.result.Result;
import com.cs.service.CourseService;
import com.cs.service.UserService;
import com.cs.vo.CourseVO;
import com.cs.vo.GetInfoUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;

import static com.cs.enumeration.OperationType.OperationType;

@Service
public class CourseServiceImpl extends ServiceImpl<ICourseMapper, Course> implements CourseService {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IStudentCourseMapper studentCourseMapper;

    @Autowired
    private ICourseMapper courseMapper;

    /**
     * 获取所有课程
     * @return
     */
    @Override
    public List<CourseVO> getAllCourse() {
        //创建一个List集合来存储所有课程
        List<CourseVO> courseVOList = new ArrayList<>();
        //创建一个查询条件对象
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        //查询所有课程
        List<Course> courseList = baseMapper.selectList(queryWrapper);
        //判断如果为空，抛出异常给前端
        if (courseList == null) {
            throw new BaseException("当前无可选课程");
        }
        //创建一个用户的查询条件对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //遍历课程列表
        for (Course course : courseList) {
            //创建一个CourseVO对象
            CourseVO courseVO = new CourseVO();
            //拷贝属性
            courseVO.setId(course.getId());
            courseVO.setCourseName(course.getCourseName());
            courseVO.setCourseContent(course.getCourseContent());
            //根据老师id查询老师姓名
            userQueryWrapper.eq("id", course.getTeacherId());
            User user = userMapper.selectOne(userQueryWrapper);
            courseVO.setTeacherName(user.getUsername());
            courseVO.setStatus(course.getStatus());
            courseVO.setStartTime(course.getStartTime());
            //将CourseVO对象添加到List集合中
            courseVOList.add(courseVO);
        }
        return courseVOList;
    }

    /**
     * 根据id获取课程
     * @param id
     * @return
     */
    @Override
    public CourseVO getCourseById(Integer id) {
        //创建一个用户的查询条件对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //根据课程id查询课程
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Course course = baseMapper.selectOne(queryWrapper);
        //判断如果为空，抛出异常给前端
        if (course == null) {
            throw new BaseException("此课程不存在");
        }
        //创建一个CourseVO对象
        CourseVO courseVO = new CourseVO();
        //拷贝属性
        courseVO.setId(course.getId());
        courseVO.setCourseName(course.getCourseName());
        courseVO.setCourseContent(course.getCourseContent());
        //根据老师id查询老师姓名
        userQueryWrapper.eq("id", course.getTeacherId());
        User user = userMapper.selectOne(userQueryWrapper);
        courseVO.setTeacherName(user.getUsername());
        courseVO.setStatus(course.getStatus());
        courseVO.setStartTime(course.getStartTime());
        return courseVO;
    }

    /**
     * 根据课程id添加课程
     * @param courseId
     * @return
     */
    @Override
    @AutoAnnouncement(com.cs.enumeration.OperationType.CHOOSE)
    public Result addCourseById(Integer courseId) {
        //获取当前用户id
        Integer userId = BaseContext.getCurrentId();
        //根据课程id查询课程
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", courseId);
        Course course = baseMapper.selectOne(queryWrapper);
        //判断如果为空，抛出异常给前端
        if (course == null) {
            throw new BaseException("此课程不存在");
        }
        //判断如果课程状态为0，抛出异常给前端
        if (course.getStatus() == 0) {
            throw new BaseException("此课程未开始");
        }
        //判断如果课程状态为2，抛出异常给前端
        if (course.getStatus() == 2) {
            throw new BaseException("此课程已结束");
        }
        //判断是否已经添加
        QueryWrapper<StudentCourse> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("course_id", courseId);
        courseQueryWrapper.eq("student_id", userId);
        StudentCourse studentCourse = studentCourseMapper.selectOne(courseQueryWrapper);
        if (studentCourse!= null) {
            throw new BaseException("此课程已添加");
        }
        //添加课程
        StudentCourse newCourse = new StudentCourse();
        newCourse.setStudentId(userId);
        newCourse.setCourseId(courseId);
        newCourse.setCreateTime(LocalDateTime.now());
        newCourse.setStatus(0);
        studentCourseMapper.insert(newCourse);
        return Result.success("添加成功");
    }

    /**
     * 根据用户id获取用户的课程
     * @param currentId
     * @return
     */
    @Override
    public List<CourseVO> getPersonalCourseSchedule(Integer currentId) {
        // 创建一个List集合来存储个人课程表
        List<CourseVO> courseVOList = new ArrayList<>();

        // 根据学生ID查询选课记录
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", currentId);
        List<StudentCourse> studentCourseList = studentCourseMapper.selectList(queryWrapper);

        // 遍历选课记录，查询对应的课程信息
        for (StudentCourse studentCourse : studentCourseList) {
            Course course = courseMapper.selectById(studentCourse.getCourseId());
            if (course != null) {
                CourseVO courseVO = new CourseVO();
                BeanUtils.copyProperties(course, courseVO);
                //根据老师id查询老师姓名
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", course.getTeacherId());
                User user = userMapper.selectOne(userQueryWrapper);
                courseVO.setTeacherName(user.getUsername());
                //将CourseVO对象添加到List集合中
                courseVOList.add(courseVO);
            }
        }

        return courseVOList;
    }
}
